<!-- 出库退货详情抽屉-->
<template>
    <div class="warehouse-details">
        <el-drawer v-model="dialogVisible" title="出库退货详情" size="1200px" direction="rtl">
            <div class="drawer-content">
                <div class="tab-header">
                    <div class="warehouse-info">
                        <el-row :gutter="28">
                            <el-col :span="4">
                                <div class="info-field">
                                    <div class="field-label">退货单号</div>
                                    <div class="field-value">{{ props.dialogRow.return_order_no || '--' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="4">
                                <div class="info-field">
                                    <div class="field-label">退货金额</div>
                                    <div class="field-value">¥{{ props.dialogRow.return_amount || '0.00' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="4">
                                <div class="info-field">
                                    <div class="field-label">退货日期</div>
                                    <div class="field-value">{{ props.dialogRow.return_date || '--' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="4">
                                <div class="info-field">
                                    <div class="field-label">客户</div>
                                    <div class="field-value">{{ props.dialogRow.customer_name || '--' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="3">
                                <div class="info-field">
                                    <div class="field-label">退货负责人</div>
                                    <div class="field-value">{{ props.dialogRow.manager_name || '--' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="3">
                                <div class="info-field">
                                    <div class="field-label">负责人电话</div>
                                    <div class="field-value">{{ props.dialogRow.manager_phone || '--' }}</div>
                                </div>
                            </el-col>
                            <el-col :span="2">
                                <div class="info-field">
                                    <div class="field-label">状态</div>
                                    <div class="field-value">
                                        <el-tag :type="getStatusType(props.dialogRow.status)" size="small">
                                            {{ props.dialogRow.status_text || '--' }}
                                        </el-tag>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </div>

                <div class="tab-container">
                    <el-tabs v-model="activeTab">
                        <!-- 基础信息 -->
                        <el-tab-pane label="基础信息" name="basic">
                            <div class="info-section">
                                <div class="section-title">
                                    <el-icon>
                                        <ArrowDown />
                                    </el-icon>
                                    <span>退货单信息</span>
                                </div>
                                <div class="info-grid">
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">退货单号：</span>
                                            <span class="value">{{ props.dialogRow.return_order_no || '--' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <span class="label">关联补库单：</span>
                                            <span class="value">{{ props.dialogRow.outbound_order_no || '--' }}</span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">退货日期：</span>
                                            <span class="value">{{ props.dialogRow.return_date || '--' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <span class="label">退货金额：</span>
                                            <span class="value">¥{{ props.dialogRow.return_amount || '0.00' }}</span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">客户：</span>
                                            <span class="value">{{ props.dialogRow.customer_name || '--' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <span class="label">状态：</span>
                                            <span class="value">
                                                <el-tag :type="getStatusType(props.dialogRow.status)" size="small">
                                                    {{ props.dialogRow.status_text || '--' }}
                                                </el-tag>
                                            </span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">退货负责人：</span>
                                            <span class="value">{{ props.dialogRow.manager_name || '--' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <span class="label">负责人电话：</span>
                                            <span class="value">{{ props.dialogRow.manager_phone || '--' }}</span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">备注：</span>
                                            <span class="value">{{ props.dialogRow.note || '--' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <span class="label">创建人：</span>
                                            <span class="value">{{ props.dialogRow.creator_name || '--' }}</span>
                                        </div>
                                    </div>
                                    <div class="info-row">
                                        <div class="info-col">
                                            <span class="label">创建时间：</span>
                                            <span class="value">{{ props.dialogRow.created_at || '--' }}</span>
                                        </div>
                                        <div class="info-col">
                                            <!-- 占位列 -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </el-tab-pane>

                        <!-- 退货产品 -->
                        <el-tab-pane label="退货产品" name="products">
                            <div class="product-content">
                                <!-- 搜索框 -->
                                <div class="search-bar">
                                    <el-input v-model="searchKeyword" placeholder="产品名称/规格型号" style="width: 250px"
                                        @input="handleProductSearch">
                                        <template #prefix>
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </div>

                                <div class="product-list">
                                    <el-table :data="filteredProductList" border style="width: 100%;" v-loading="productLoading">
                                        <el-table-column label="产品名称" prop="product_name" width="auto" />
                                        <el-table-column label="规格型号" prop="specification" width="auto" />
                                        <el-table-column label="拆零单位" prop="open_unit_name" width="auto" align="center" />
                                        <el-table-column label="补库数量" prop="out_num" width="auto" align="center" />
                                        <el-table-column label="补库单价" prop="price" width="auto" align="center">
                                            <template #default="scope">
                                                ¥{{ parseFloat(scope.row.price || 0).toFixed(2) }}
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="退货数量" width="auto" align="center">
                                            <template #default="scope">
                                                <span class="return-count">{{ scope.row.return_num || 0 }}</span>
                                            </template>
                                        </el-table-column>

                                    </el-table>

                                    <!-- 表格底部合计 -->
                                    <div class="table-footer">
                                        <div class="summary-item">产品种类：<span>{{ productList.length }}</span></div>
                                        <div class="summary-item">退货数量（个）：<span>{{ totalReturnCount }}</span></div>
                                        <div class="summary-item">退货总金额（元）：<span>¥{{ totalReturnAmount }}</span></div>
                                    </div>
                                </div>

                            </div>
                        </el-tab-pane>

                        <!-- 退货入库情况 -->
                        <el-tab-pane label="退货入库情况" name="inbound">
                            <div class="inbound-content">
                                <div class="search-bar">
                                    <el-input v-model="inboundSearch" placeholder="产品名称/规格型号/出库单号" style="width: 300px">
                                        <template #prefix>
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </template>
                                    </el-input>

                                    <el-select v-model="inboundStatus" placeholder="请选择入库状态"
                                        style="width: 150px;margin-left: 10px;">
                                        <el-option label="全部入库" value="all" />
                                        <el-option label="未入库" value="pending" />
                                        <el-option label="已入库" value="approved" />
                                    </el-select>
                                </div>

                                <div class="inbound-list">
                                    <el-table :data="inboundList" border style="width: 100%">
                                        <el-table-column label="产品名称" prop="product_name" width="auto" />
                                        <el-table-column label="规格型号" prop="specification" width="150" />
                                        <el-table-column label="单位" prop="unit" width="auto" />
                                        <el-table-column label="入库状态" prop="status_text" width="auto" />
                                        <el-table-column label="入库数量" prop="inbound_count" width="auto" />
                                        <el-table-column label="退货数量" prop="return_count" width="auto" />
                                        <el-table-column label="入库单号" prop="inbound_order_no" width="auto" />
                                        <el-table-column label="入库仓库" prop="warehouse_name" width="auto" />
                                        <el-table-column label="入库人" prop="operator_name" width="auto" />
                                        <el-table-column label="入库时间" prop="inbound_time" width="auto" />
                                    </el-table>
                                </div>

                                <!-- 分页 -->
                                <div class="pagination">
                                    <Pagination v-model:current-page="inboundPage" v-model:page-size="inboundPageSize"
                                        :page-sizes="[10, 20, 50, 100]" :total="inboundTotal"
                                        layout="total, sizes, prev, pager, next, jumper" />
                                </div>
                            </div>
                        </el-tab-pane>

                        <!-- 审批流程 -->
                        <el-tab-pane label="审批流程" name="approval">
                            <div class="approval-content">
                                <div class="search-bar">
                                    <el-input v-model="approvalSearch" placeholder="退货单号/审批人" style="width: 300px">
                                        <template #prefix>
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </div>

                                <!-- 审批列表 -->
                                <div class="approval-list">
                                    <el-table :data="approvalList" border style="width: 100%">
                                        <el-table-column label="退货单号" prop="return_order_no" width="140" />
                                        <el-table-column label="退货金额" prop="return_amount" width="120" />
                                        <el-table-column label="审批状态" prop="approval_status" width="auto" />
                                        <el-table-column label="审批人" prop="approver_name" width="auto" />
                                        <el-table-column label="审批时间" prop="approval_time" width="auto" />
                                        <el-table-column label="审批意见" prop="approval_note" width="auto" />
                                        <el-table-column label="创建人" prop="creator_name" width="auto" />
                                        <el-table-column label="创建时间" prop="created_at" width="auto" />
                                    </el-table>
                                </div>

                                <div class="pagination">
                                    <Pagination v-model:current-page="approvalPage" v-model:page-size="approvalPageSize"
                                        :page-sizes="[10, 20, 50, 100]" :total="approvalTotal"
                                        layout="total, sizes, prev, pager, next, jumper" />
                                </div>
                            </div>
                        </el-tab-pane>

                        <!-- 操作记录 -->
                        <el-tab-pane label="操作记录" name="operation">
                            <div class="operation-content">
                                <div class="operation-list">
                                    <el-table :data="operationList" border style="width: 100%">
                                        <el-table-column label="操作时间" prop="operation_time" width="180" />
                                        <el-table-column label="操作人" prop="operator_name" width="120" />
                                        <el-table-column label="操作类型" prop="operation_type" width="120" />
                                        <el-table-column label="操作内容" prop="operation_content" min-width="200" />
                                        <el-table-column label="备注" prop="remark" width="150" />
                                    </el-table>
                                </div>

                                <div class="pagination">
                                    <Pagination v-model:current-page="operationPage"
                                        v-model:page-size="operationPageSize" :page-sizes="[10, 20, 50, 100]"
                                        :total="operationTotal" layout="total, sizes, prev, pager, next, jumper" />
                                </div>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ArrowDown, Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import Pagination from "@/components/Pagination.vue";
import api from "@/api";

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    dialogRow: {
        type: Object,
        default: () => ({})
    }
});

const emit = defineEmits(['update:dialogVisible']);

const dialogVisible = computed({
    get: () => props.dialogVisible,
    set: (val) => emit('update:dialogVisible', val)
});

// 获取状态标签类型
const getStatusType = (status: number) => {
    const statusTypeMap: { [key: number]: string } = {
        0: 'info',     // 待提交
        1: 'warning',  // 审核中
        2: 'success',  // 审核完成
        3: 'danger'    // 审核拒绝
    };
    return statusTypeMap[status] || 'info';
};

const activeTab = ref('basic');

// 退货产品相关
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const productList = ref<any[]>([]);
const productLoading = ref(false);

// 获取退货产品列表
const getProductList = async () => {
    if (!props.dialogRow.id) {
        console.warn('退货单ID不存在，无法获取产品列表');
        return;
    }

    productLoading.value = true;
    try {
        const params = {
            id: props.dialogRow.id,
            keywords: searchKeyword.value.trim(),

        };

        const res = await api.Outbound.getoutboundReturnProductListByOrderId(params);
        
        if (res.code === 200) {
            productList.value = res.data.product_data || [];
            total.value = res.data.total || productList.value.length;
            console.log('获取退货产品列表成功:', productList.value);
        } else {
            ElMessage.error(res.message || '获取退货产品列表失败');
            productList.value = [];
            total.value = 0;
        }
    } catch (error) {
        console.error('获取退货产品列表失败:', error);
        ElMessage.error('获取退货产品列表失败');
        productList.value = [];
        total.value = 0;
    } finally {
        productLoading.value = false;
    }
};

// 移除前端过滤，直接使用API返回的数据
const filteredProductList = computed(() => {
    return productList.value;
});

// 防抖搜索定时器
let searchTimer: number | null = null;

// 处理产品搜索 - 添加防抖
const handleProductSearch = () => {
    // 清除之前的定时器
    if (searchTimer) {
        clearTimeout(searchTimer);
    }
    
    // 设置新的定时器，300ms后执行搜索
    searchTimer = setTimeout(() => {
        currentPage.value = 1; // 搜索时重置到第一页
        getProductList();
    }, 300);
};

// 处理分页大小变化
const handlePageSizeChange = (val: number) => {
    pageSize.value = val;
    currentPage.value = 1;
    getProductList();
};

// 处理页码变化
const handlePageChange = (val: number) => {
    currentPage.value = val;
    getProductList();
};

// 计算单个产品的退货金额
const calculateProductReturnAmount = (product: any) => {
    const returnNum = parseFloat(product.return_num || 0);
    const price = parseFloat(product.price || 0);
    const amount = returnNum * price;
    return amount.toFixed(2);
};

// 计算退货总数量
const totalReturnCount = computed(() => {
    return productList.value.reduce((total: number, product: any) => {
        return total + (Number(product.return_num) || 0);
    }, 0);
});

// 计算退货总金额
const totalReturnAmount = computed(() => {
    const total = productList.value.reduce((sum: number, product: any) => {
        const returnNum = parseFloat(product.return_num || 0);
        const price = parseFloat(product.price || 0);
        return sum + (returnNum * price);
    }, 0);
    return total.toFixed(2);
});

// 监听弹窗显示状态，当打开时获取产品列表
watch(() => props.dialogVisible, (newVal) => {
    if (newVal && props.dialogRow.id) {
        // 重置搜索和分页状态
        searchKeyword.value = '';
        currentPage.value = 1;
        pageSize.value = 10;
        getProductList();
    }
});

// 监听退货单数据变化，重新获取产品列表
watch(() => props.dialogRow.id, (newId) => {
    if (newId && props.dialogVisible) {
        // 重置搜索和分页状态
        searchKeyword.value = '';
        currentPage.value = 1;
        pageSize.value = 10;
        getProductList();
    }
});

// 监听搜索关键词变化（但通过handleProductSearch防抖处理）
watch(searchKeyword, () => {
    if (props.dialogVisible && props.dialogRow.id) {
        handleProductSearch();
    }
});

// 退货入库情况相关
const inboundSearch = ref(''); //退货入库的搜索 
const inboundStatus = ref('all');//退货入库的状态
const inboundPage = ref(1);
const inboundPageSize = ref(10);
const inboundTotal = ref(0);
const inboundList = ref([]);

// 审批流程相关
const approvalSearch = ref('');
const approvalPage = ref(1);
const approvalPageSize = ref(10);
const approvalTotal = ref(0);
const approvalList = ref([]);

// 操作记录相关
const operationPage = ref(1);
const operationPageSize = ref(10);
const operationTotal = ref(0);
const operationList = ref([]);
</script>

<style lang="scss" scoped>
//表格样式
::v-deep .product-list {
    .el-table {
        --el-table-header-bg-color: rgba(235, 236, 240, 1);

        th {
            color: #444;
            font-weight: bold;
        }
    }
}

//表格样式
::v-deep .inbound-list {
    .el-table {
        --el-table-header-bg-color: rgba(235, 236, 240, 1);

        th {
            color: #444;
            font-weight: bold;
        }
    }
}

//表格样式
::v-deep .approval-list {
    .el-table {
        --el-table-header-bg-color: rgba(235, 236, 240, 1);

        th {
            color: #444;
            font-weight: bold;
        }
    }
}

//表格样式
::v-deep .operation-list {
    .el-table {
        --el-table-header-bg-color: rgba(235, 236, 240, 1);

        th {
            color: #444;
            font-weight: bold;
        }
    }
}

//分页样式
.pagination {
    width: calc(100% - 1000px);
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding-top: 10px;
}

.warehouse-details {
    .drawer-content {
        height: calc(100% - 60px);
        overflow-y: auto;

        .tab-header {
            padding: 10px;
            background-color: #F5F7FA;

            .warehouse-info {
                .info-field {
                    padding: 10px;
                    display: flex;
                    flex-direction: column;
                    border-radius: 4px;

                    .field-label {
                        color: #909399;
                        font-size: 13px;
                        margin-bottom: 4px;
                    }

                    .field-value {
                        color: #333;
                        font-weight: 500;
                        font-size: 14px;
                    }
                }
            }
        }

        .tab-container {
            padding: 20px;

            :deep(.el-tabs__header) {
                margin-bottom: 20px;
            }
        }

        .info-section {
            margin-bottom: 24px;

            .section-title {
                background-color: #F5F7FA;
                padding: 12px 10px;
                display: flex;
                align-items: center;
                gap: 8px;
                margin-bottom: 16px;
                font-size: 14px;
                font-weight: bold;
                color: #333;

                .el-icon {
                    font-size: 16px;
                    color: #626aef;
                }
            }

            .info-grid {
                padding: 16px;
                border-radius: 4px;

                .info-row {
                    display: flex;
                    margin-bottom: 16px;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .info-col {
                        flex: 1;
                        display: flex;
                        align-items: center;

                        .label {
                            width: 80px;
                            color: #000;
                            flex-shrink: 0;
                            margin-left: 8px;
                            font-size: 12px;
                        }

                        .value {
                            color: #333;
                            flex: 1;
                            display: inline-block;
                            padding: 6px;
                            font-size: 14px;
                            background-color: #F5F7FA;
                        }
                    }
                }
            }
        }
    }
}

:deep(.el-drawer) {
    .el-drawer__body {
        padding: 0;
    }
}

:deep(.el-tabs__nav-wrap::after) {
    height: 1px;
}

:deep(.el-tabs__active-bar) {
    background-color: #626aef;
}

:deep(.el-tabs__item.is-active) {
    color: #626aef;
}

:deep(.el-tabs__item:hover) {
    color: #626aef;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
}

.product-list,
.inbound-list,
.approval-list,
.operation-list {
    margin-bottom: 16px;
}

.table-footer {
    display: flex;
    justify-content: space-between;
    padding: 16px 0;
    color: #333;
    background-color: #f8f9fa;
    border-radius: 4px;
    margin-top: 16px;

    .summary-item {
        font-weight: 500;
        
        span {
            color: #626aef;
            font-weight: bold;
        }
    }
}

.pagination {
    display: flex;
    justify-content: flex-end;
}

:deep(.el-table) {
    --el-table-header-bg-color: #F5F7FA;

    th {
        background-color: var(--el-table-header-bg-color);
        color: #606266;
        font-weight: 500;
    }
}

:deep(.el-button) {
    &.is-plain {
        &:hover {
            color: #626aef;
            border-color: #626aef;
        }
    }
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
    background-color: #626aef;
    border-color: #626aef;
    box-shadow: -1px 0 0 0 #626aef;
}

// 产品相关样式
.return-count {
    color: #e6a23c;
    font-weight: bold;
}

.return-amount {
    color: #67c23a;
    font-weight: bold;
}
</style>
